﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Common.Logging;

namespace Common
{
    /// <summary>
    /// Redirects output from a TextWriter to the logger (ie for tracing Linq Queries)
    /// </summary>
    public class LogProxy : TextWriter
    {
        private ILog _log;
        private LogLevel _level;

        public LogProxy(ILog log, LogLevel level)
        {
            _log = log;
            _level = level;
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }

        StringBuilder sb = new StringBuilder();

        public override void Write(char value)
        {
            if ((value == 10 || value == 13) && sb.Length > 0)
            { Flush(); }
            else
            { sb.Append(value); }
        }
        public override void Write(string value)
        {
            sb.Append(value);
            Flush();
        }
        public override void WriteLine(string value)
        { Write(value); }
        public override void WriteLine()
        {}
        private void Flush()
        {
            String text = sb.ToString();
            sb.Length = 0;
            switch (_level)
            {
                case LogLevel.Debug:
                    _log.Debug(text);
                    break;
                case LogLevel.Error:
                    _log.Error(text);
                    break;
                case LogLevel.Warn:
                    _log.Warn(text);
                    break;
                case LogLevel.Info:
                    _log.Info(text);
                    break;
                case LogLevel.Fatal:
                    _log.Fatal(text);
                    break;
                case LogLevel.Trace:
                default:
                    _log.Trace(text);
                    break;
            }
        }
    }
}
